package com.zfc.life.controller.backend;

import com.zfc.life.comm.AjaxResult;
import com.zfc.life.domain.Users;
import com.zfc.life.service.UsersService;
import com.zfc.life.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zfc
 * @Date 2024/5/23 15:04
 * @Description LoginController
 */
@RestController
@RequestMapping("/backend")
public class LoginController {
    @Autowired
    private UsersService usersService;

    @PostMapping("/login")
    public AjaxResult login(@RequestBody Users users) {
        Users usersInfo = usersService.selectByLoginNameAndLoginPassword(users);

        if (StringUtils.isEmpty(usersInfo)){
            return AjaxResult.error("用户名或密码错误！！！");
        }

        Map<String,Object> map = new HashMap<>();
        try {
            Map<String, String> payload = new HashMap<>();
            payload.put("id",usersInfo.getId()+"");
            payload.put("name",usersInfo.getLoginName());
            // 生成jwt令牌
            String token = JWTUtils.getToken(payload);
            map.put("token",token);  // 响应token
        } catch (Exception e) {
            map.put("msg",e.getMessage());
        }

        return AjaxResult.success(map);
    }
}
